import { DirectiveBinding } from 'vue'
import { DeElement } from '.'

// 防抖指令 v-debounce
const debounce = {
  mounted: function (el: DeElement, binding: DirectiveBinding) {
    let timer: NodeJS.Timeout
    // 监视键盘事件
    el._keyups = () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        binding.value()
      }, 300)
    }
    el.addEventListener('keyup', el._keyups)
    // 监视点击事件
    el._clicks = () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        binding.value()
      }, 300)
    }
    el.addEventListener('click', el._clicks)
  },
  unmounted(el: DeElement) {
    el.removeEventListener('click', el._clicks)
    el.removeEventListener('keyup', el._keyups)
  }
}
// 权限指令 v-permission
export default debounce
